package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"net/http"
	"net/http/httputil"
	"path/filepath"
)

type Conf struct {
	Local  string `yaml:"local"`
	Remote string `yaml:"remote"`
}

func main() {
	filePath, err := filepath.Abs("./conf.yaml")
	fmt.Println("配置文件: " + filePath)
	yamlFile, err := ioutil.ReadFile(filePath)
	if err != nil {
		fmt.Println(err.Error())
	}
	conf := &Conf{}
	err = yaml.Unmarshal(yamlFile, conf)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Printf("Local=%s | Remote=%s \n", conf.Local, conf.Remote)
	if len(conf.Remote) <= 0 {
		conf.Remote = "10.4.9.111:24402"
	}
	if len(conf.Local) <= 0 {
		conf.Local = "127.0.0.1:8101"
	}
	fmt.Printf("Local=%s | Remote=%s \n", conf.Local, conf.Remote)

	pathArray := []string{
		"/user/topLogin.json",
		"/mobile/user/login.json",
		"/mobile/wechat/user/loginAndBindUser.json",
		"/mobile/wechat/user/bindUser.json",
		"/app/user/login.json",
		"/app/member/bindUser/userSwitch.json",
		"/user/topQuickLogin.json",
		"/user/bindUser/userSwitch.htm",
		"/user/autoLogin.json",
		"/user/toScanLogin.json",
		"/app/site/userSwitch.json",
		"/app/user/quickLogin.json",
		"/mobile/wechat/user/quickLoginAndBindUser.json",
		"/mobile/wechat/user/getUserOpenid.json",
		"/mobile/wechat/bindUser/userSwitch.json",
	}

	var proxy http.Handler = &httputil.ReverseProxy{
		Director: func(request *http.Request) {
			flag := false
			for _, path := range pathArray {
				if path == request.URL.Path {
					flag = true
					break
				}
			}
			request.URL.Scheme = "http"
			if flag {
				request.URL.Host = conf.Remote
			} else {
				request.URL.Host = conf.Local
			}
			fmt.Printf("%s | %s | %s  | %s \n", request.URL.Scheme, request.URL.Host, request.URL.Path, request.URL.RawPath)
		},
	}
	err = http.ListenAndServe(":8102", proxy)
	fmt.Println(err)
}
